//
//  ErrorInterceptorPlugin.swift
//  Network
//
//  Created by sunlubo on 2017/2/21.
//  Copyright © 2017年 milanosoft. All rights reserved.
//

import Foundation
import Moya
import Result
import SwiftyJSON

/// 对API调用失败进行拦截处理
public final class ErrorInterceptorPlugin: PluginType {
    
    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target _: TargetType) {
        switch result {
        case let .success(response):
            guard let jsonObject = try? response.mapJSON() else { return }
            
            let json = JSON(jsonObject)
            if json["resultCode"].stringValue == "ERROR" {
                Log.error(json["message"].stringValue)
                showMessage(json["message"].stringValue)
            } else if json["resultCode"].stringValue == "INVALID_TOKEN" {
                Log.error(json["message"].stringValue)
                showMessage("账户已在其他设备登陆")
                
                //                currentUser?.logout()
                //                if let navController = currentWindow.rootViewController as? UINavigationController {
                //                    navController.popToRootViewControllerAnimated(true)
                //                    presentLoginController()
                //                }
            }
        case let .failure(error):
            Log.error(error.localizedDescription)
            showMessage("请求错误")
        }
    }
}
